package com.shimao.celnet.payment.service.impl;

import com.github.pagehelper.PageHelper;
import com.shimao.celnet.payment.form.ASysRoleForm;
import com.shimao.celnet.payment.form.SelectTree;
import com.shimao.celnet.payment.mapper.ASysPermissionMapper;
import com.shimao.celnet.payment.mapper.ASysRoleMapper;
import com.shimao.celnet.payment.mapper.ASysRolePermissionMapper;
import com.shimao.celnet.payment.mapper.ASysUserRoleMapper;
import com.shimao.celnet.payment.model.ASysPermission;
import com.shimao.celnet.payment.model.ASysRolePermission;
import com.shimao.celnet.payment.model.ASysRole;
import com.shimao.celnet.payment.service.ASysRoleService;
import com.shimao.celnet.payment.util.FinalUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.util.StringUtil;
import org.apache.log4j.Logger;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ASysRoleServiceImpl extends BaseServiceImpl<ASysRole> implements ASysRoleService {
    protected Logger logger = Logger.getLogger(this.getClass());

    @Autowired(required = false)
    private ASysRoleMapper aSysRoleMapper;

    @Autowired(required = false)
    private ASysRolePermissionMapper aSysRolePermissionMapper;

    @Autowired(required = false)
    private ASysUserRoleMapper aSysUserRoleMapper;

    @Autowired(required = false)
    private ASysPermissionMapper aSysPermissionMapper;

    /**
     * 分页查询
     * @param formBean
     * @param pageNum
     * @param length
     * @return
     */
    @Override
    public ASysRoleForm getByPage(ASysRoleForm formBean, int pageNum, int length) {
        logger.info("分页查询--开始");
        Example example = new Example(ASysRole.class);
        Example.Criteria criteria = example.createCriteria();
        if (StringUtil.isNotEmpty(formBean.getRoleName())) {
            criteria.andLike("roleName", "%" + formBean.getRoleName() + "%");
        }

        //分页查询
        PageHelper.startPage(pageNum, length);
        List<ASysRole> roleList = getByExample(example);
        formBean.setPageInfo(roleList);

        logger.info("分页查询--结束");

        return  formBean;
    }

    /**
     * 根据用户GUID，取得用户所有角色列表
     * @param userGuid
     * @return
     */
    @Override
    public List<ASysRole> getRoleByUser(String userGuid) {
        logger.info("根据用户GUID，取得用户所有角色列表");
        return aSysRoleMapper.selectRoleByUser(userGuid);
    }


    /**
     * 保存角色，角色权限信息
     * @param aSysRole\
     * @param permissionGuidMap 角色权限Guid  list
     */
    @Override
    @CacheEvict(cacheNames="roles", allEntries=true)
    @Transactional(propagation= Propagation.REQUIRES_NEW,readOnly=false,rollbackFor={Exception.class})
    public int save(ASysRole aSysRole,Map<String, String> permissionGuidMap) {
        logger.info("保存角色，角色权限信息--开始");
        String userGuid = (String) SecurityUtils.getSubject().getSession().getAttribute("userSessionId");
        aSysRole.setGuid(getGuid());
        aSysRole.setUpdateUserGuid(userGuid);
        aSysRole.setCreatedUserGuid(userGuid);
        //保存角色
        int retCnt = save(aSysRole);
        logger.debug("保存角色信息");
        String roleGuid = aSysRole.getGuid();

        //新增角色权限
        updateRolePermission(roleGuid,permissionGuidMap);

        logger.info("保存角色，角色权限信息--结束");
        return retCnt;
    }

    /**
     * 修改角色，角色权限信息
     * @param aSysRole
     * @param permissionGuidMap 角色权限Guid  list
     */
    @Override
    @CacheEvict(cacheNames="roles", allEntries=true)
    @Transactional(propagation= Propagation.REQUIRES_NEW ,readOnly=false,rollbackFor={Exception.class})
    public int update(ASysRole aSysRole,Map<String, String> permissionGuidMap) {
        logger.info("修改：角色，角色权限信息--开始");
        String userGuid = (String) SecurityUtils.getSubject().getSession().getAttribute("userSessionId");
        aSysRole.setUpdateUserGuid(userGuid);

        logger.debug("修改：角色");
        int retCnt =  update(aSysRole);
        String roleGuid = aSysRole.getGuid();

        //更新角色权限
        updateRolePermission(roleGuid,permissionGuidMap);

        logger.info("修改：角色，角色权限信息--结束");
        return retCnt;
    }

    /**
     * 根据角色guid，删除角色信息
     * @param roleGuid
     */

    @Override
    @CacheEvict(cacheNames="roles", allEntries=true)
    @Transactional(propagation= Propagation.REQUIRES_NEW,readOnly=false,rollbackFor={Exception.class})
    public int delete(String roleGuid) {
        int retCnt = 0;
        //根据角色guid，删除角色权限
        logger.info("删除：根据角色guid，删除角色权限");
        aSysRolePermissionMapper.deleteByRole(roleGuid);

        logger.info("删除：根据角色guid，删除用户角色");
        aSysUserRoleMapper.deleteByRole(roleGuid);

        //删除角色
        logger.info("删除：根据角色guid，删除角色");
        retCnt = aSysRoleMapper.deleteByPrimaryKey(roleGuid);
      return retCnt;
    }

    /**
     * 权限树生成
     * @param roleGuid
     * @return
     */
    public  List<SelectTree>  creatPermissionTree(String roleGuid) {
        List<SelectTree> retTreeList = new ArrayList<SelectTree>();

        //角色拥有的权限map
        Map<String, String> guidMap = new HashMap<String, String>();
        if(StringUtils.isNotEmpty(roleGuid)){
            //角色对应权限取得
            List<ASysPermission> aSysPermissionRole=aSysPermissionMapper.selectRolePermission(roleGuid);
            for(ASysPermission aSysPermission:aSysPermissionRole){
                guidMap.put(aSysPermission.getGuid(),aSysPermission.getGuid());
            }
        }

        List<ASysPermission> allList = aSysPermissionMapper.selectAllPermission();

        String fistMenuNm = "";//一级菜单名称
        String secMenuNm = "";//二级菜单名称
        String superType = "";//上一个节点等级（一级，二级，按钮操作）
        for(ASysPermission permission:allList){
            SelectTree selectTree = new SelectTree();
            selectTree.setGuid(permission.getGuid());//节点value
            selectTree.setOptionText(permission.getPermissionName());//节点名称
            selectTree.setStrSelected(FinalUtil.DISABLE);//没有选中
            //树节点被勾选
            if(StringUtils.isNotEmpty(guidMap.get(permission.getGuid()))) {
                selectTree.setStrSelected(FinalUtil.ENABLE);//选中
            }


            //父级权限名称设置
            if(FinalUtil.PERMISSION_TYPE_1.equals(permission.getType()) ){
                //一级菜单
                superType = permission.getType();
                selectTree.setDataSection(FinalUtil.PERMISSION_ROOT);
                fistMenuNm = FinalUtil.PERMISSION_ROOT  + FinalUtil.PERMISSION_MENU_BIAS
                        + permission.getPermissionName();
            }else if(FinalUtil.PERMISSION_TYPE_2.equals(permission.getType()) ){
                //二级菜单
                superType = permission.getType();
                secMenuNm = fistMenuNm + FinalUtil.PERMISSION_MENU_BIAS
                        + permission.getPermissionName();
                selectTree.setDataSection(fistMenuNm);

                retTreeList.add(selectTree);
            }else  if(FinalUtil.PERMISSION_TYPE_9.equals(permission.getType()) ){
                if(FinalUtil.PERMISSION_TYPE_2.equals(superType) ){
                    retTreeList.remove(retTreeList.size()-1);
                }
                //数据（按钮）权限
                superType = permission.getType();
                selectTree.setDataSection(secMenuNm);//父级权限名称设置

                retTreeList.add(selectTree);
            }

        }
        return retTreeList;
    }

    /**
     * 保存角色权限信息
     * @param roleGuid
     * @param permissionGuidMap 角色权限Guid  list
     */
    public int  updateRolePermission(String roleGuid,Map<String, String> permissionGuidMap) {
        logger.debug("修改：角色权限信息--开始");
        int retCnt = 0;

        //删除：角色对应权限
        aSysRolePermissionMapper.deleteByRole(roleGuid);

        Map<String, String> allGuidMap = new HashMap<String, String>();
        //guidMap中二级菜单权限对应一级菜单权限，按钮权限对应的二级权限添加
        for (String permissionGuid : permissionGuidMap.keySet()) {
            ASysPermission aSysPermission=aSysPermissionMapper.selectByPrimaryKey(permissionGuid);
            allGuidMap.put(permissionGuid,permissionGuid);

            //按钮权限对应的二级权限
            if(FinalUtil.PERMISSION_TYPE_9.equals(aSysPermission.getType())){
                allGuidMap.put(aSysPermission.getParentGuid(),aSysPermission.getParentGuid());
                ASysPermission aSysPermission_Parent = aSysPermissionMapper.selectByPrimaryKey(aSysPermission.getParentGuid());
                allGuidMap.put(aSysPermission_Parent.getParentGuid(),aSysPermission_Parent.getParentGuid());
            }

            //二级菜单权限对应一级菜单权限
            if(FinalUtil.PERMISSION_TYPE_2.equals(aSysPermission.getType())){
                allGuidMap.put(aSysPermission.getParentGuid(),aSysPermission.getParentGuid());
            }
       }

        String loginUserGuid = (String) SecurityUtils.getSubject().getSession().getAttribute("userSessionId");

        //新增：角色对应权限
        for (String permissionGuid : allGuidMap.keySet()) {
            ASysRolePermission aSysRolePermission = new ASysRolePermission();
            aSysRolePermission.setGuid(aSysRolePermissionMapper.selectGuid());
            aSysRolePermission.setRoleGuid(roleGuid);
            aSysRolePermission.setPermissionGuid(permissionGuid);
            aSysRolePermission.setUpdateUserGuid(loginUserGuid);
            aSysRolePermission.setCreatedUserGuid(loginUserGuid);
            aSysRolePermissionMapper.insert(aSysRolePermission);
        }

        logger.debug("修改：角色权限信息--结束");
        return retCnt;

    }
}
